<template>
    <div v-if="isshow" :prop="image" class="select-img">
        <el-upload
                class="avatar-uploader"
                :action="uploadImgUrl"
                :disabled="true"
                :on-preview="handlePictureCardPreview"
                :file-list="fileLists"
                :limit="limit"
                :headers="headers"
        >
            <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
    </div>
    <div v-else :prop="image">
        <el-upload
                :action="uploadImgUrl"
                :on-remove="(file, fileList)=> handleRemove(file, fileList, images)"
                :on-success="(response, file, fileList)=> onSuccess(response, file, fileList, images)"
                :on-preview="handlePictureCardPreview"
                :before-upload="beforeUpload"
                :on-error="handleUploadError"
                :file-list="fileLists"
                :limit="limit"
                :headers="headers"
                :on-exceed="onExceed"
        >
            <el-button size="small" type="primary">点击上传</el-button>
        </el-upload>
    </div>
</template>

<script>
import {imgUrl, getFileList} from '@/api/common/imgUpload'
import {getToken} from '@/utils/auth'
import {getFdfsImg} from '@/utils/common'

export default {
    name: 'UpImgs',
    model: {
        // 使用model， 这儿2个属性，prop属性说，我要将msg作为该组件被使用时（此处为aa组件被父组件调用）v-model能取到的值，event说，我emit ‘cc’ 的时候，参数的值就是父组件v-model收到的值。
        prop: 'image',
        event: 'cc'
    },
    props: {
        image: {
            type: String,
            default: null
        },
        limit: {
            type: Number,
            default: 1
        },
        isshow: {
            type: Boolean,
            default: false
        }
    },
    data() {
        return {
            downUrl: process.env.VUE_APP_BASE_API+"/upload/fdfs/download",
            uploadImgUrl: process.env.VUE_APP_BASE_API + '/upload/fdfs/img', // 上传的文件服务器地址
            headers: {
                Authorization: 'Bearer ' + getToken(),
            },
            isLimit: false,
            isUpload: false,
            images: this.image,
            dialogImageUrl: '',
            dialogVisible: false,
            fileLists: []
        }
    },
    watch: {
        image(newImg, oldImg) {
            this.images = this.image
            if (!this.isUpload) {
                this.fileLists = this.getFileList(this.image, this.fileLists)
            }
        }
    },
    created() {
        this.fileLists = this.getFileList(this.image, this.fileLists)
        if (this.fileLists.length === this.limit) {
            this.isLimit = true
        }
    },
    methods: {
        getFileList,
        imgUrl,
        fn2() {
            this.$emit('cc', this.images) // 这儿是关键 update:snycTest 自定义事件会告诉父组件将父组件的 test值改为this.snycTest+1，并传回给子组件。
        },
        beforeUpload(file) {
            const isLt2M = file.size / 1024 / 1024 < 10
            if (!isLt2M) {
                this.$message.error('上传文件大小不能超过 10MB!')
                return false
            }
            this.loading = this.$loading({
                lock: true,
                text: '上传中',
                background: 'rgba(0, 0, 0, 0.7)',
            })
            this.fn2()
            return true
        },
        onSuccess(response, file, fileList, img) {
            this.loading.close()
            if (fileList.length === this.limit) {
                this.isLimit = true
            }
            if (!img) {
                img = response.url
            } else {
                img += ',' + response.url
            }
            this.images = img
            this.isUpload = true
            this.fn2()
        },
        handleRemove(file, fileList, img) {
            if (!img) {
                return
            }
            const imgs = img.split(',')
            // 移除 删除的文件
            imgs.splice(this.getDeleteIndex(imgs, file), 1)
            this.images = imgs.join(',')
            this.isUpload = true
            this.fn2()
            // if (file.imgUrl) {
            //   deleteImg({ fileUrl: imgUrl(file.imgUrl) })
            // } else {
            //   deleteImg({ fileUrl: imgUrl(file.response.url) })
            // }
        },
        handlePictureCardPreview(file) {
            console.log("xxxxx",file)
            // this.dialogImageUrl = file.url
            // this.dialogVisible = true
            // window.open(getFdfsImg(file.url));
            if(file.url){
                var tempPath = file.url.split("?")
                var elemIF = document.createElement("iframe");
                elemIF.src = this.downUrl + "?urlPath="+tempPath[0]+"&fileName="+encodeURI(encodeURI(tempPath[1]))+"&t="+new Date();
                elemIF.style.display = "none";
                document.body.appendChild(elemIF);
            }
        },
        handleUploadError() {
            this.$message({
                type: 'error',
                message: '上传失败',
            })
            this.loading.close()
        },
        // 获取当前删除文件的索引
        getDeleteIndex(imgs, file) {
            if (imgs.length > 0) {
                for (let i = 0; i < imgs.length; i++) {
                    if (file.url !== undefined && file.url.indexOf(imgs[i]) != -1) {
                        return i
                    }
                    if (
                        file.response !== undefined &&
                        file.response.url.indexOf(imgs[i]) != -1
                    ) {
                        return i
                    }
                }
            }
            return 0
        },
        onExceed(event, file, fileList) {
            this.$message.error('超出文件上传数量限制，限制' + this.limit + '个')
        }
    }
}
</script>
<style>
    .select-img .el-upload {
        display: none;
    }
</style>
